package com.bookstore.servlet;

import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import com.bookstore.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

@WebServlet("/client/user.do")
public class UserServlet extends HttpServlet {
    UserService userService=new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action=req.getParameter("action");
        if("register".equals(action)){
            register(req,resp);
        }
        if("login".equals(action)){
            login(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    private void register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int result=0;
        String email=req.getParameter("email");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String telephone=req.getParameter("telephone");
        String gender=req.getParameter("gender");
        String introduction=req.getParameter("introduction");
        User user = new User(null,username,password,gender,email,telephone,introduction,null,0,0,new Date());
        result=userService.register(user);
        System.out.println(result);
        if(result>0){
            resp.getWriter().write("1");
        }else{
            resp.getWriter().write("0");
        }
    }
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        User user=new User(null,username,password,null,null,null,null,null,null,null,null);
        User loginUser=userService.login(user);
        HttpSession session = req.getSession();
        session.setAttribute("user", loginUser);
        Object user1 = session.getAttribute("user");
        if(user1==null){
            //强制跳转回登录页面
        }
        if(loginUser!=null){
            resp.getWriter().write("1");
        }else{
            resp.getWriter().write("0");
        }

    }
}
